/*
 * Copyright 2019 Web3 Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.web3j.web3jevmexample;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.Hash;
import org.web3j.java.APIConsumer;
import org.web3j.java.LinkToken;
import org.web3j.java.Operator;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Numeric;

import java.util.ArrayList;
import java.util.List;

public class DeployContract {

    public static void main(String... args) throws Exception {
        // 账户地址和私钥
        String fromAddress = "0x627306090abaB3A6e1400e9345bC60c78a8BEf57"; // 创世文件_内置账户地址
        String privateKey = "c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3";// 内置账户私钥
        Credentials originalCredentials = Credentials.create(privateKey);
        //System.out.println("Original Credentials Address : " + originalCredentials.getAddress());

        //String linkTokenAddress = "0x8cdaf0cd259887258bc13a92c0a6da92698644c0";     // LINK 合约地址
        //String linkTokenEIP55 = "0x8CdaF0CD259887258Bc13a92C0a6dA92698644C0";     // LINK 合约 EIP55 格式地址
        String linkTokenAddress = "0xf204a4ef082f5c04bb89f7d5e6568b796096735a";     // LINK 合约地址
        String linkTokenEIP55 = "0xf204a4Ef082f5c04bB89F7D5E6568B796096735a";     // LINK 合约 EIP55 格式地址

        String operatorAddress = "0xf12b5dd4ead5f743c6baa640b0216200e89b60da";      // Operator 合约地址
        String operatorEIP55 = "0xF12b5dd4EAD5F743C6BaA640B0216200e89B60Da";      // Operator 合约 EIP55 格式地址


        //String apiConsumerAddress = "0x9fbda871d559710256a2502a2517b794b482db40";   // APIConsumer合约地址( 0 fee )
        //String apiConsumerAddress = "0xde5491f774f0cb009abcea7326342e105dbb1b2e";   // APIConsumer合约地址 ( 100 fee )
        //String apiConsumerEIP55 = "0xdE5491f774F0Cb009ABcEA7326342E105dbb1B2E";   // APIConsumer合约地址 EIP55 格式地址
        String apiConsumerAddress = "0x8cdaf0cd259887258bc13a92c0a6da92698644c0";   // APIConsumer合约地址 ( 100 fee )

        String atestnetConsumer = "0x8273e4b8ed6c78e252a9fca5563adfcc75c91b2a";     // ATestnetConsumer合约地址
        String evmChainAddress = "0x71965FB3ceAc089Fab7CC69a99C85E2397929523";      // EVM Chain Accounts (chainlink在私有链上的账户地址)
        String jobid = "8d8c66be716c4bcf9a59c5d8e70123db";

        //Web3j web3j = Web3j.build(new HttpService("http://localhost:8545"));
        Web3j web3j = Web3j.build(new HttpService("http://192.168.1.162:8545"));

        //Web3ClientVersion clientVersion = web3j.web3ClientVersion().send();
        //String version = clientVersion.getWeb3ClientVersion();
        //System.out.println("Connected to Ethereum node: " + version);


        // 部署 LinkToken 合约
        System.out.println("Starting LinkToken deploy...");
        LinkToken linkToken =
                LinkToken.deploy(web3j, originalCredentials, new DefaultGasProvider()).send();

        //获取合约地址
        System.out.println("LinkToken address: " + linkToken.getContractAddress());
        System.out.println("LinkToken EIP-55 address: " +toChecksumAddress(linkToken.getContractAddress()));


/**
        // 部署 Operator 合约
        System.out.println("Starting Operator deploy...");
        Operator operator =
                Operator.deploy(web3j, originalCredentials, new DefaultGasProvider(),linkTokenEIP55,toChecksumAddress(fromAddress)).send();//获取合约地址
        System.out.println("Operator address: " + operator.getContractAddress());
        System.out.println("Operator EIP-55 address: " +toChecksumAddress(operator.getContractAddress()));
*/

/**
        // 部署 APIConsumer 合约
        System.out.println("Starting APIConsumer deploy...");
        APIConsumer apiConsumer =
        APIConsumer.deploy(web3j, originalCredentials, new DefaultGasProvider()).send();//获取合约地址
        System.out.println("APIConsumer address: " + apiConsumer.getContractAddress());
        System.out.println("APIConsumerEIP55 address: " + toChecksumAddress(apiConsumer.getContractAddress()));
*/

/**
        // 部署 ATestnetConsumer 合约
        System.out.println("Starting APIConsumer deploy...");
        ATestnetConsumer aTestnetConsumer=
                ATestnetConsumer.deploy(web3j, originalCredentials, new DefaultGasProvider()).send();//获取合约地址
        System.out.println("ATestnetConsumer address: " + aTestnetConsumer.getContractAddress());
*/

/**
        ATestnetConsumer atc = ATestnetConsumer.load(atestnetConsumer,web3j,originalCredentials,new DefaultGasProvider());
        // 检查调用者的地址是否在授权列表中
        String chainlinkTokenAddress = atc.getChainlinkToken().send();
        System.out.println("ChainlinkToken Address: " + chainlinkTokenAddress);

        //atc.requestEthereumPrice(operatorAddress,jobid);
*/


/**
        Operator operator =Operator.load(operatorEIP55,web3j,originalCredentials,new DefaultGasProvider());
        // 设置授权的发送者(授权链下oracle地址)
        List<String> senders = new ArrayList<>();
        senders.add(evmChainAddress);
        operator.setAuthorizedSenders(senders).send();
        System.out.println("设置授权的发送者(授权链下oracle地址)成功");

        // 查看授权的发送者
        List<String> authorizedSenders = operator.getAuthorizedSenders().send();
        for (int i = 0; i <authorizedSenders.size(); i++) {
           System.out.println("authorizedSenders["+i+"]: "+authorizedSenders.get(i));
        }
        Boolean isAuthorizedSender = operator.isAuthorizedSender(evmChainAddress).send();
        System.out.println("evmChainAddress是否是授权的发送者: "+isAuthorizedSender);

        //System.out.println("Operator EIP55 address: "+toChecksumAddress(operatorAddress));
        //System.out.println("LinkToken EIP55 address: "+toChecksumAddress(linkTokenAddress));
*/



        web3j.shutdown();

    }



    // 转成EIP55格式的地址
    public static String toChecksumAddress(String address) {
        if ((address != null && !address.trim().isEmpty()) && address.startsWith("0x")) {
            String addressWithoutPrefix = address.substring(2);
            String hashedAddress = Numeric.toHexStringNoPrefix(Hash.sha3(addressWithoutPrefix.toLowerCase().getBytes()));

            StringBuilder checksumAddress = new StringBuilder("0x");
            for (int i = 0; i < addressWithoutPrefix.length(); i++) {
                // 根据哈希值的每个字符决定当前字符是大写还是小写
                if (Integer.parseInt(String.valueOf(hashedAddress.charAt(i)), 16) > 7) {
                    checksumAddress.append(Character.toUpperCase(addressWithoutPrefix.charAt(i)));
                } else {
                    checksumAddress.append(addressWithoutPrefix.charAt(i));
                }
            }
            return checksumAddress.toString();
        }
        throw new IllegalArgumentException("Invalid address format");
    }

}

